package com.small.sentinel.slots.statistic.metric.occupy;

import com.small.sentinel.slots.statistic.base.LeapArray;
import com.small.sentinel.slots.statistic.base.WindowWrap;
import com.small.sentinel.slots.statistic.data.MetricBucket;

public class OccupiableBucketLeapArray extends LeapArray<MetricBucket> {

    private final FutureBucketLeapArray borrowArray;

    public OccupiableBucketLeapArray(int sampleCount, int intervalInMs) {
        // This class is the original "CombinedBucketArray".
        super(sampleCount, intervalInMs);
        this.borrowArray = new FutureBucketLeapArray(sampleCount, intervalInMs);
    }

    @Override
    public MetricBucket newEmptyBucket(long time) {
        MetricBucket newBucket = new MetricBucket();
        MetricBucket borrowBucket = borrowArray.getWindowValue(time);
        //将旧数据放入新创建的存储空间
        if (borrowBucket != null) {
            newBucket.reset(borrowBucket);
        }

        return newBucket;
    }

    @Override
    protected WindowWrap<MetricBucket> resetWindowTo(WindowWrap<MetricBucket> w, long time) {
        // 重置开始时间
        w.resetTo(time);
        MetricBucket borrowBucket = borrowArray.getWindowValue(time);
        if (borrowBucket != null) {
            w.value().reset();
            //然后将在borrowArray中当前时间对用的时间窗口中统计的通请求通过数添加到在array数组中的当前时间的时间窗口中
            w.value().addPass((int)borrowBucket.pass());
        } else {
            w.value().reset();
        }

        return w;
    }

}
